package com.dag.eagleshop.core.account.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Set;

/**
 * http请求工具类
 */
@Slf4j
public final class HttpUtils {

	private HttpUtils(){}

	public static final String GET = "GET";
	public static final String POST = "POST";
	public static final String ENCODING = "utf-8";

	/**
	 * JSON请求 参数和返回报文都是json
	 */
	public static <T> T httpPostByJson(String requestUrl, Object body, Class<T> clazz) {
		String responseJson = httpPostByJson(requestUrl, null, body);
		return JSON.parseObject(responseJson, clazz);
	}


	/**
	 * JSON请求
	 * 参数和返回报文都是json
	 * 支持请求头
	 */
	public static <T> T httpPostByJson(String requestUrl, Map<String, String> header, Object body, Class<T> clazz) {
		String responseJson = httpPostByJson(requestUrl, header, body);
		return JSON.parseObject(responseJson, clazz);
	}


	/**
	 * JSON请求 参数和返回报文都是json
	 */
	public static String httpPostByJson(String requestUrl, Map<String, String> header, Object body) {
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			HttpURLConnection.setFollowRedirects(true);
			if(header != null){
				Set<String> keySet = header.keySet();
				for (String key : keySet) {
					conn.setRequestProperty(key, header.get(key));
				}
			}
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(10000);
			conn.setRequestProperty("Content-type", "application/json;charse=UTF-8");
			conn.setRequestMethod(POST);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.connect();

			if(body != null){
				try {
					// 获取URLConnection对象对应的输出流
					OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream());
					// 发送请求参数
					os.write(JSON.toJSONString(body));
					os.flush();
					os.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			InputStream is = conn.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(is, ENCODING));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = read.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			conn.disconnect();
			return sb.toString();
		} catch (Exception e) {
			log.error("httpPost请求失败", e);
			throw new RuntimeException("httpPost请求失败！原因：" + e.getMessage());
		}
	}


	/** 发起POST请求 参数&拼接 返回字符串 */
	public static String httpPost(String requestUrl, String params) {
		return http(requestUrl, POST, params);
	}


	/** 发起GET请求 参数&拼接 返回字符串 */
	public static String httpGet(String requestUrl) {
		return http(requestUrl, GET, null);
	}


	/** 发起GET请求 参数&拼接 返回字符串 */
	public static <T> T httpGetByJson(String requestUrl, Class<T> clazz) {
		String responseJson = http(requestUrl, GET, null);
		return JSON.parseObject(responseJson, clazz);
	}

	private static String http(String requestUrl, String method, String params) {
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			HttpURLConnection.setFollowRedirects(true);
			conn.setRequestMethod(method);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.connect();

			if(params != null){
				try {
					// 获取URLConnection对象对应的输出流
					OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream());
					// 发送请求参数
					os.write(params);
					os.flush();
					os.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			InputStream is = conn.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(is, ENCODING));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = read.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			conn.disconnect();
			return sb.toString();
		} catch (Exception e) {
			log.error("http请求失败", e);
			throw new RuntimeException("http请求失败！原因：" + e.getMessage());
		}
	}
}
